//
// Created by henry on 2025/11/7.
//

#include "student/front_user.h"

frontuser* find_student_by_id(int id) {
    // 静态变量，用于存储查询结果，确保函数返回后内存有效
    static frontuser student;
    memset(&student, 0, sizeof(frontuser)); // 清空结构体

    const char *sql = "SELECT id, username, balance, number FROM stu_user WHERE id = ?";
    sqlite3_stmt *stmt = NULL;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);

    if (rc != SQLITE_OK) {
        fprintf(stderr, "find_student_by_id: 预编译SQL失败! %s\n", sqlite3_errmsg(db));
        return NULL;
    }

    sqlite3_bind_int(stmt, 1, id);
    rc = sqlite3_step(stmt);

    if (rc == SQLITE_ROW) {
        // 成功查询到数据，填充到结构体中
        student.id = sqlite3_column_int(stmt, 0);
        strncpy(student.username, (const char*)sqlite3_column_text(stmt, 1), sizeof(student.username) - 1);
        strncpy(student.balance, (const char*)sqlite3_column_text(stmt, 2), sizeof(student.balance) - 1);
        strncpy(student.number, (const char*)sqlite3_column_text(stmt, 3), sizeof(student.number) - 1);
    } else {
        // 未查询到数据
        sqlite3_finalize(stmt);
        return NULL;
    }

    sqlite3_finalize(stmt);
    return &student;
}

//登陆
int front_user_login() {
    frontuser user;
    printf("输入用户名:");
    scanf("%19s", user.username);

    // SQL 查询 id (整数) 和 balance (文本)
    const char *sql = "SELECT id, balance FROM stu_user where username=?";

    sqlite3_stmt *stmt = NULL;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "front_user_login:编译出错! %s\n", sqlite3_errmsg(db));
        return -1;
    }

    sqlite3_bind_text(stmt, 1, user.username, -1, SQLITE_TRANSIENT);
    rc = sqlite3_step(stmt);

    if (rc != SQLITE_ROW) {
        printf("账号不存在，请注册之后使用!\n");
        sqlite3_finalize(stmt);
        return -1;
    }

    // 读取 id (整数)
    user.id = sqlite3_column_int(stmt, 0);

    // 读取 balance (文本)
    const char* db_balance_str = (const char*)sqlite3_column_text(stmt, 1);
    if (db_balance_str != NULL) {
        // 使用 strncpy 更安全，防止缓冲区溢出
        strncpy(user.balance, db_balance_str, sizeof(user.balance) - 1);
        user.balance[sizeof(user.balance) - 1] = '\0'; // 确保字符串以空字符结尾
    } else {
        // 如果数据库中该字段为 NULL，给一个默认值
        strcpy(user.balance, "0.00");
    }

    // 打印最终结果
    printf("登录成功！序列号为：%d，卡内余额为：%s 元\n", user.id, user.balance);

    sqlite3_finalize(stmt);
    return 0;
}


//注册
int front_user_register(){
    frontuser user;
    memset(&user, 0, sizeof(frontuser));

    printf("输入姓名:");
    if (scanf("%49s", user.username) != 1) {
        printf("输入错误!\n");
        return -1;
    }
    while (getchar() != '\n');

    printf("输入学号:");
    if (scanf("%19s", user.number) != 1) {
        printf("输入错误!\n");
        return -1;
    }
    while (getchar() != '\n');

    printf("充值金额:");
    if (scanf("%19s", user.balance) != 1) {
        printf("输入错误!\n");
        return -1;
    }
    while (getchar() != '\n');

    const char *check_sql = "select count(*) from stu_user where number=?";
    sqlite3 *stmt;
    int rc = sqlite3_prepare_v2(db, check_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "front_user_register:校验学号失败! %s\n", sqlite3_errmsg(db));
        return -1;
    }

    // 绑定用户名参数
    sqlite3_bind_text(stmt, 1, user.number, -1, SQLITE_TRANSIENT);
    rc = sqlite3_step(stmt);
    int count = 0;
    if (rc == SQLITE_ROW) {
        count = sqlite3_column_int(stmt, 0);
    }
    sqlite3_finalize(stmt); // 释放预编译语句

    if (count > 0) {
        printf("绑定学号失败，请输入正确学号!\n");
        return -1;
    }

    // 插入新用户信息到数据库
    const char *insert_sql = "insert into stu_user (username, balance, number) values (?, ?, ?)";
    rc = sqlite3_prepare_v2(db, insert_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "front_user_register:插入用户信息编译出错! %s\n", sqlite3_errmsg(db));
        return -1;
    }

    rc = sqlite3_bind_text(stmt, 1, user.username, -1, SQLITE_TRANSIENT);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "绑定用户名失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }

    rc = sqlite3_bind_text(stmt, 2, user.balance, -1, SQLITE_TRANSIENT);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "充值失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }

    rc = sqlite3_bind_text(stmt, 3, user.number, -1, SQLITE_TRANSIENT);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "绑定学号失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }



// 执行插入
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "front_user_register:注册用户信息失败! %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        return -1;
    }

// 显式提交事务（SQLite默认自动提交，此处为了兼容性和可读性）
    sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);

    printf("注册成功!\n");
    printf("注册成功！姓名：%s，学号：%s 卡内余额: %s \n", user.username, user.number, user.balance);
    sqlite3_finalize(stmt);
    return 0;
}


//定义学生的删除信息
int front_user_delete(sqlite3 *db, int student_id) {
    // 1. 检查参数合法性
    if (db == NULL || student_id <= 0) {
        fprintf(stderr, "delete student : 参数错误（db为空或ID无效）\n");
        return -1;
    }

    // 2. 参数化SQL（防注入，仅绑定ID）
    const char *sql = "DELETE FROM stu_user WHERE id = ?;"; // 学生表名假设为 student
    sqlite3_stmt *stmt = NULL;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "delete student : 准备SQL失败 : %s\n", sqlite3_errmsg(db));
        return -2;
    }

    // 3. 绑定ID参数（索引1，整数类型）
    sqlite3_bind_int(stmt, 1, student_id);

    // 4. 执行删除（DELETE语句返回SQLITE_DONE）
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "delete student : 执行删除失败 : %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt); // 释放句柄
        return -2;
    }

    // 5. 检查删除行数
    int deleted_rows = sqlite3_changes(db);
    if (deleted_rows == 0) {
        printf("delete student : 未找到ID为 %d 的学生，无记录删除\n", student_id);
    } else {
        printf("delete student : 删除成功！影响行数：%d\n", deleted_rows);
        sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL); // 手动提交事务
    }

    // 6. 释放资源
    sqlite3_finalize(stmt);
    return 0;
}

void user_delete_ui(sqlite3 *db) {
    printf("\n--- 进入学生信息删除界面 ---\n");
    int student_id;

    // 1. 获取用户输入的学生ID（含合法性校验）
    printf("请输入要删除的学生ID（正数）：");
    if (scanf("%d", &student_id) != 1) {
        printf("输入无效！请输入一个整数ID。\n");
        while (getchar() != '\n'); // 清空输入缓冲区
        return;
    }
    while (getchar() != '\n'); // 清空残留换行符

    // 2. 调用数据库层函数执行删除
    int result = front_user_delete(db, student_id);

    // 3. 反馈结果
    if (result == 0) {
        printf("学生信息删除操作已完成！\n");
    } else {
        printf("学生信息删除失败，错误码：%d\n", result);
    }

    printf("--- 退出学生信息删除界面 ---\n");
}